<?php

namespace App\Providers;

use App\Models\Database;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class DatabaseProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {

    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        if (defined('TOKEN_USER')) {
            $db = Database::where('default', 1)->where('user_id', TOKEN_USER)->first();
            $config = [
                'driver'    => $db->driver,
                'host'      => $db->db_host,
                'port'      => $db->db_port,
                'database'  => 'zhangblog', //$db->db_name,
                'username'  => $db->db_user,
                'password'  => $db->db_password,
                'charset'   => $db->db_charset,
                'collation' => $db->db_collation,
                'prefix'    => $db->frefix ?? ''
            ];

            $this->app->get('config')->set('database.connections.app', $config);
            DB::purge('app');
            DB::reconnect('app');
        }
    }
}
